package com.augus.config;

import com.augus.mapper.SmbmsUserMapper;
import com.augus.pojo.SmbmsUser;
import com.augus.service.SmbmsUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpSession;

// 自定义的 UserRealm  extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {

  @Autowired
  SmbmsUserService smbmsUserService;

  // 授权
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    System.out.println("执行了 --> doGetAuthorizationInfo 授权");
    // SimpleAuthorizationInfo
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    info.addStringPermission("user:add");

    // 拿到当前登录的这个对象
    Subject subject = SecurityUtils.getSubject();
    SmbmsUser currentUser = (SmbmsUser) subject.getPrincipal();// 拿到SmbmsUser对象

    // 设置当前用户的权限
    info.addStringPermission(currentUser.getPerms());

    return info;
  }
  // 认证
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    System.out.println("执行了 --> doGetAuthenticationInfo 认证");

    // 用户名,密码 ~ 数据中取
   /* String name = "root";
    String password = "123456";*/

    // 连接真实的数据库
    UsernamePasswordToken userToken = (UsernamePasswordToken) token;
    SmbmsUser smbmsUser = smbmsUserService.queryUserByName(userToken.getUsername());
    // 账号认证
    if (smbmsUser == null) { // 没有这个人
      return null;// UnknownAccountException
    }

    Subject subject = SecurityUtils.getSubject();
    Session session = subject.getSession();;
    session.setAttribute("loginUser",smbmsUser);

    // 账号认证
    /*if (!userToken.getUsername().equals(name)){
     return null;// 排除异常 UnknownAccountException
    }*/

    // 可以加密: MD5:e10adc3949ba59abbe56e057f20f883e MD5盐值加密:e10adc3949ba59abbe56e057f20f883euserename
    // 密码认证: shiro 做 ,加密了

    return new SimpleAuthenticationInfo(smbmsUser,smbmsUser.getUserPassword(),"");
  }
}
